package entity

import (
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"nspel/nspel"
	"strconv"
)

type Label struct {
	Id    int64  `orm:"pk;auto;column(id)"`
	Value string `orm:"column(value)"`
	Color string `orm:"column(color)"`
}

func (*Label) TableName() string {
	return "label"
}

func init() {
	orm.RegisterModel(new(Label))
}

func (l *Label) SelectAllByValueColor(value string, color string) (err error) {
	key := "label"
	hashKey := "value[\"" + value + "\"].color[\"" + color + "\"]"
	err = nspel.RedisHgetJson(key, hashKey, l)
	if err == nil {
		return nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	l.Value = value
	l.Color = color
	err = nspel.GetOrmEngine().Read(l, "value", "color")
	if err != nil {
		return err
	}
	nspel.RedisHsetJson(key, hashKey, l)
	return nil
}

func (l *Label) Insert() error {
	_, err := nspel.GetOrmEngine().Insert(l)
	return err
}

func (l *Label) Count() (int64, error) {
	return nspel.GetOrmEngine().QueryTable(l.TableName()).Count()
}

func (l *Label) Update(columns ...string) error {
	_, err := nspel.GetOrmEngine().Update(l, columns...)
	return err
}

func (l *Label) SelectAllById(id int64) (err error) {
	key := "label"
	hashKey := "id[\"" + strconv.FormatInt(id, 10) + "\"]"
	err = nspel.RedisHgetJson(key, hashKey, l)
	if err == nil {
		return nil
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	l.Id = id
	err = nspel.GetOrmEngine().Read(l)
	if err != nil {
		return err
	}
	nspel.RedisHsetJson(key, hashKey, l)
	return nil
}

func (l *Label) CustomSelect(ormEng *orm.QuerySeter, hashKey string) (labels []Label, err error) {
	key := "label"
	err = nspel.RedisHgetJson(key, hashKey, &labels)
	if err == nil {
		return
	}
	if err != redis.ErrNil {
		nspel.Error(err)
	}
	_, err = (*ormEng).All(&labels)
	if err != nil || len(labels) == 0 {
		return
	}
	nspel.RedisHsetJson(key, hashKey, labels)
	return
}

func (l *Label) DeleteById(id int64) (err error) {
	l.Id = id
	_, err = nspel.GetOrmEngine().Delete(l)
	return
}
